/*
 * Copyright (C) 2015 备胎金服
 * 未经授权允许不得进行拷贝和修改
 *   http://www.btjf.com/
 */
package com.zhangman.framework.implementation;

import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import com.zhangman.framework.Music;
import java.io.IOException;

/**
 * Created by zhangman on 2016/11/1 11:39.
 * Email: zhangman523@126.com
 */
public class AndroidMusic
    implements Music, MediaPlayer.OnCompletionListener, MediaPlayer.OnSeekCompleteListener,
    MediaPlayer.OnPreparedListener, MediaPlayer.OnVideoSizeChangedListener {
  MediaPlayer mMediaPlayer;
  boolean isPrepared = false;

  public AndroidMusic(AssetFileDescriptor assetFileDescriptor) {
    mMediaPlayer = new MediaPlayer();
    try {
      mMediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(),
          assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
      mMediaPlayer.prepare();
      isPrepared = true;
      mMediaPlayer.setOnCompletionListener(this);
      mMediaPlayer.setOnSeekCompleteListener(this);
      mMediaPlayer.setOnPreparedListener(this);
      mMediaPlayer.setOnVideoSizeChangedListener(this);
    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException("Couldn't load music");
    }
  }

  @Override public void play() {
    if (mMediaPlayer.isPlaying()) {
      return;
    }
    try {
      synchronized (this) {
        if (!isPrepared) {
          mMediaPlayer.prepare();
        }
        mMediaPlayer.start();
      }
    } catch (IllegalStateException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  @Override public void stop() {
    if (mMediaPlayer.isPlaying()) {
      this.mMediaPlayer.stop();
    }
    synchronized (this) {
      isPrepared = false;
    }
  }

  @Override public void pause() {
    if (this.mMediaPlayer.isPlaying()) {
      mMediaPlayer.pause();
    }
  }

  @Override public void setLooping(boolean looping) {
    mMediaPlayer.setLooping(looping);
  }

  @Override public void setVolume(float volume) {
    mMediaPlayer.setVolume(volume, volume);
  }

  @Override public boolean isPlaying() {
    return mMediaPlayer.isPlaying();
  }

  @Override public boolean isStopped() {
    return !isPrepared;
  }

  @Override public boolean isLooping() {
    return mMediaPlayer.isLooping();
  }

  @Override public void dispose() {
    if (mMediaPlayer.isPlaying()) {
      mMediaPlayer.stop();
    }
    mMediaPlayer.release();
  }

  @Override public void seekBegin() {
    mMediaPlayer.seekTo(0);
  }

  @Override public void onCompletion(MediaPlayer mediaPlayer) {
    synchronized (this) {
      isPrepared = false;
    }
  }

  @Override public void onPrepared(MediaPlayer mediaPlayer) {
    synchronized (this) {
      isPrepared = true;
    }
  }

  @Override public void onSeekComplete(MediaPlayer mediaPlayer) {

  }

  @Override public void onVideoSizeChanged(MediaPlayer mediaPlayer, int i, int i1) {

  }
}
